package be.nvlooy.moviereminder.common;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@SuppressWarnings("rawtypes")
public class EnumExposureHandlerInterceptor extends HandlerInterceptorAdapter {

    private Set<Class<? extends Enum>> enumClasses = new HashSet<Class<? extends Enum>>();

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        for (Class<? extends Enum> enumClass : enumClasses) {
            final String enumClassName = enumClass.getSimpleName();
            final Enum[] enums = enumClass.getEnumConstants();

            // put them into map, so that we can access them like ENUMCLS.ENUMVALUE
            Map<String, Enum> map = new HashMap<String, Enum>(enums.length);
            for (Enum anEnum : enums) {
                map.put(anEnum.name(), anEnum);
            }

            // seting to scope
            request.setAttribute(enumClassName, map);
        }
    }

    public void setEnumClasses(Set<Class<? extends Enum>> enumClasses) {
        this.enumClasses = enumClasses;
    }
}
